import { GetAddress, GetWeather } from '@/api/blog-api'

export default {
  namespaced: true,
  state: {
    weather: {},
    address: {}
  },
  mutations: {
    setWeather (state, { weather = {} }) {
      state.weather = weather
    },
    /**
     * @description 隐藏
     * @param {Object} state state
     */
    setAddress (state, { address = {} }) {
      state.address = address
    }
  },
  actions: {
    InitAddress ({ state }) {
      return new Promise(async (resolve) => {
        let address = localStorage.getItem('mlb-address')
        if (address) {
          address = JSON.parse(address)
          // 每四小时更新
          if (address.ts - new Date().getTime() < -1000 * 60 * 60 * 4) {
            await GetAddress()
              .then(res => {
                res.ts = new Date().getTime()
                state.address = res
                localStorage.setItem('mlb-address', JSON.stringify(res))
                resolve()
              }).catch(err => {
                console.log('err: ', err)
              })
          } else {
            state.address = address
            resolve()
          }
        } else {
          await GetAddress()
            .then(res => {
              res.ts = new Date().getTime()
              state.address = res
              localStorage.setItem('mlb-address', JSON.stringify(res))
              resolve()
            }).catch(err => {
              console.log('err: ', err)
            })
        }
      })
    },

    InitWeather ({ state }) {
      return new Promise(async (resolve) => {
        let weather = localStorage.getItem('mlb-weather')
        if (weather) {
          weather = JSON.parse(weather)
          // 每三小时更新
          if (weather.ts - new Date().getTime() < -1000 * 60 * 60 * 3) {
            await GetWeather(state.address.query)
              .then(res => {
                res.ts = new Date().getTime()
                state.weather = res
                localStorage.setItem('mlb-weather', JSON.stringify(res))
                resolve()
              }).catch(err => {
                console.log('err: ', err)
              })
          } else {
            resolve()
            state.weather = weather
          }
        } else {
          await GetWeather(state.address.query)
            .then(res => {
              res.ts = new Date().getTime()
              state.weather = res
              localStorage.setItem('mlb-weather', JSON.stringify(res))
              resolve()
            }).catch(err => {
              console.log('err: ', err)
            })
        }
      })
    },
    Init ({ dispatch }) {
      return new Promise(async resolve => {
        await dispatch('InitAddress')
        await dispatch('InitWeather')
        resolve()
      })
    }
  }
}
